<template>
  <div class="jsbos-common-layout">
    <div class="jsbos-common-layout-left">
      <div class="jsbos-common-title">
        <h2>题库目录</h2>
        <span class="options">
          <el-dropdown>
            <el-link icon="icon-ym icon-ym-mpMenu" :underline="false" />
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item @click.native="getTreeView()"
                >刷新数据</el-dropdown-item
              >
              <el-dropdown-item @click.native="toggleExpand(true)"
                >展开全部</el-dropdown-item
              >
              <el-dropdown-item @click.native="toggleExpand(false)"
                >折叠全部</el-dropdown-item
              >
            </el-dropdown-menu>
          </el-dropdown>
        </span>
      </div>
      <el-scrollbar
        class="jsbos-common-el-tree-scrollbar"
        v-loading="treeLoading"
      >
        <el-tree
          ref="treeBox"
          :data="treeData"
          :props="treeProps"
          :default-expand-all="expands"
          highlight-current
          :expand-on-click-node="false"
          node-key="id"
          @node-click="handleNodeClick"
          class="jsbos-common-el-tree"
          v-if="refreshTree"
          :filter-node-method="filterNode"
        >
          <span
            class="custom-tree-node"
            slot-scope="{ data }"
            :title="data.fullName"
          >
            <i :class="data.icon"></i>
            <span class="text" :title="data.fullName">{{ data.fullName }}</span>
          </span>
        </el-tree>
      </el-scrollbar>
    </div>

    <div class="jsbos-common-layout-center">
      <el-row class="jsbos-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <el-col :span="6">
            <el-form-item :label="$t('common.keyword')">
              <el-input
                v-model="listQuery.keyword"
                placeholder="名称"
                clearable
                @keyup.enter.native="search()"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="jsbos-common-layout-main jsbos-flex-main">
        <div class="jsbos-common-head">
          <div>
            <!-- v-has="'btn_add'" -->
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
          </div>
          <div class="jsbos-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JSBOS-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screen-full isContainer />
          </div>
        </div>
        <jsbos-table
          v-loading="listLoading"
          :data="list"
          @sort-change="sortChange"
        >
          <el-table-column
            prop="fullName"
            label="题库名称"
            width="0"
            align="left"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="题库目录"
            width="0"
            prop="categoryId"
            algin="left"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.categoryId | dynamicTreeText(treeData) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="totalQuestion"
            label="总题数"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ getTotalQuestion(scope.row.questions) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="selectTi"
            label="单选题"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.questions.selectTi ? scope.row.questions.selectTi : 0
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="multiple"
            label="多选题"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.questions.multiple ? scope.row.questions.multiple : 0
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="determine"
            label="判断题"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.questions.determine
                  ? scope.row.questions.determine
                  : 0
              }}
            </template>
          </el-table-column>
          <el-table-column
            prop="blank"
            label="填空题"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.questions.blank ? scope.row.questions.blank : 0 }}
            </template>
          </el-table-column>
          <el-table-column
            prop="answers"
            label="问答题"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{
                scope.row.questions.answers ? scope.row.questions.answers : 0
              }}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="cases"
            label="案例题"
            :align="'center'"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope">
              {{ scope.row.questions.cases ? scope.row.questions.cases : 0 }}
            </template>
          </el-table-column> -->
          <el-table-column
            prop="creatorUserId"
            label="创建用户"
            width="150"
            :align="'left'"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="creatorTime"
            label="创建时间"
            width="180"
            :align="'left'"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="lastModifyUserId"
            label="修改用户"
            width="150"
            :align="'left'"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            prop="lastModifyTime"
            label="修改时间"
            width="180"
            :align="'left'"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="操作" width="150" fixed="right">
            <template slot-scope="scope">
              <el-button type="text" @click="goQuestionList(scope.row.id)"
                >管理
              </el-button>
              <!-- v-has="'btn_edit'" -->
              <el-button type="text" @click="addOrUpdateHandle(scope.row.id)"
                >编辑
              </el-button>
              <!-- v-has="'btn_remove'" -->
              <el-button
                type="text"
                class="jsbos-table-delBtn"
                @click="handleDel(scope.row.id)"
                >删除
              </el-button>
              <!-- v-has="'btn_detail'" -->
              <!-- <el-button type="text" @click="goDetail(scope.row.id)"
                >详情
              </el-button> -->
            </template>
          </el-table-column>
        </jsbos-table>
        <pagination
          :total="total"
          :page.sync="listQuery.currentPage"
          :limit.sync="listQuery.pageSize"
          @pagination="initData"
        />
      </div>
    </div>
    <JSBOS-Form
      v-if="formVisible"
      ref="JSBOSForm"
      @refresh="refresh"
      :categoryIdOptions="categoryOptions"
      :categoryIdProps="categoryProps"
    />
    <Detail
      v-if="detailVisible"
      ref="Detail"
      @refresh="detailVisible = false"
      :categoryIdOptions="categoryOptions"
      :categoryIdProps="categoryProps"
    />
    <QuestionListDialog
      ref="QuestionListDialog"
      v-if="questionListVisible"
      @close="closeQuestionListDialog"
      :menuId="menuId"
    ></QuestionListDialog>
  </div>
</template>

<script>
import { getSelector, getCategorySelector } from "@/views/exam/api/category";
import { getList, Delete } from "@/views/exam/api/questionLibrary";
import JSBOSForm from "./Form";
import Detail from "./Detail";
import QuestionListDialog from "./questionListDialog";

export default {
  name: "question-library-list",
  components: { JSBOSForm, Detail, QuestionListDialog },
  data() {
    return {
      folderType: "question", // 目录类型：question题目目录;paper试卷目录;exam考试目录
      isAdministrator: false,
      companyId: "",
      detailVisible: false,
      questionListVisible: false,
      query: {
        enCode: undefined,
        fullName: undefined,
      },
      list: [],
      listLoading: true,
      total: 0,
      listQuery: {
        keyword: "",
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      },
      formVisible: false,

      filterText: "",
      treeLoading: false,
      expands: true,
      refreshTree: true,
      treeData: [],
      treeProps: {
        children: "children",
        label: "name",
        value: "id",
      },
      treeActiveId: "",
      categoryOptions: [],
      categoryProps: {
        children: "children",
        label: "fullName",
        value: "id",
      },
    };
  },
  computed: {
    menuId() {
      return this.$route.meta.modelId || "";
    },
  },
  created() {
    this.isAdministrator = this.$store.getters.userInfo.isAdministrator;
    this.companyId = this.$store.getters.userInfo.organizeId;
    this.query.companyId = this.companyId;
    this.getTreeView(true);
    this.getCategoryOptions();
  },
  methods: {
    // 总题数
    getTotalQuestion(questions) {
      var totalQuestion = 0;
      if (questions) {
        Object.values(questions).forEach((value) => {
          totalQuestion += value;
        });
      }
      return totalQuestion;
    },
    closeQuestionListDialog(isRefresh) {
      this.questionListVisible = false;
      if (isRefresh) this.initData();
    },
    goQuestionList(id) {
      this.questionListVisible = true;
      this.$nextTick(() => {
        this.$refs.QuestionListDialog.init(id);
      });
    },
    getCategoryOptions() {
      // 获取所属目录
      getCategorySelector({
        folderType: this.folderType,
        parentId: "-1",
        menuId: this.menuId,
      }).then((res) => {
        this.categoryOptions = res.data;
      });
    },
    goDetail(id) {
      this.detailVisible = true;
      this.$nextTick(() => {
        this.$refs.Detail.init(id);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    getTreeView(isInit) {
      this.treeLoading = true;
      var data = {
        folderType: this.folderType,
        companyId: this.query.companyId,
        menuId: this.menuId,
      };
      getSelector(data)
        .then((res) => {
          let topItem = {
            fullName: "全部",
            hasChildren: true,
            id: "-1",
            children: res.data.list,
          };
          this.treeData = [topItem];
          this.$nextTick(() => {
            this.treeLoading = false;
            if (isInit) this.initData();
          });
        })
        .catch(() => {
          this.treeLoading = false;
        });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.fullName.indexOf(value) !== -1;
    },
    toggleExpand(expands) {
      this.refreshTree = false;
      this.expands = expands;
      this.$nextTick(() => {
        this.refreshTree = true;
        this.$nextTick(() => {
          this.$refs.treeBox.setCurrentKey(this.parentId);
        });
      });
    },
    getNodePath(node) {
      let fullPath = [];
      const loop = (node) => {
        if (node.level) fullPath.unshift(node.data);
        if (node.parent) loop(node.parent);
      };
      loop(node);
      return fullPath;
    },
    handleNodeClick(data, node) {
      this.treeActiveId = data.id;
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.query.categoryId = data.id;
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      };
      this.initData();
    },
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        menuId: this.menuId,
      };
      getList(_query).then((res) => {
        var _list = [];
        for (let i = 0; i < res.data.list.length; i++) {
          let _data = res.data.list[i];
          _list.push(_data);
        }
        this.list = _list;
        this.total = res.data.pagination.total;

        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          Delete(id).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JSBOSForm.init(id, this.menuId);
      });
    },
    search() {
      this.initData();
    },
    refresh(isInitData) {
      this.formVisible = false;
      if (isInitData) this.initData();
    },
    resetListQuery() {
      this.listQuery = {
        keyword: "",
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatorTime",
      };
    },
    resetQuery() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
    },
    reset() {
      this.resetListQuery();
      this.resetQuery();
      this.initData();
    },
  },
};
</script>
